package com.xiaoke.java;

/**
 * 测试Object类中的finalize()方法、即对象的finalization机制
 * @author yd
 * @version 1.0
 * @date 2022/3/4 19:37
 */
public class CanReliveObj {

    public static CanReliveObj obj; //类变量,属于GC Root

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("调用当前类重写的finalize方法");
        obj = this;//当前待回收的对象在finalize()方法与引用链上的一个对象obj建立了联系
    }

    public static void main(String[] args) {

        try {
            obj = new CanReliveObj();
            //对象第一次成功拯救自己
            obj = null;
            System.gc();//调用垃圾回收器
            System.out.println("第一次GC");
            //因为Finalizer线程优先级很低，暂停2秒，以等待它
            Thread.sleep(2000);
            if (obj == null){
                System.out.println("obj is dead");
            } else {
                System.out.println("obj is still alive");
            }

            System.out.println("第二次 gc");
            obj = null;
            System.gc();//调用垃圾回收器
            //因为Finalizer线程优先级很低，暂停2秒，以等待它
            Thread.sleep(2000);
            if (obj == null){
                System.out.println("obj is dead");
            } else {
                System.out.println("obj is still alive");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }


}
